package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.common.utils.RedisConstants;
import com.hmdp.common.utils.UserHolder;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDto;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IUserService userService;
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        if (followUserId == null || isFollow == null) {
            throw new RuntimeException("参数传递异常");
        }

        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            throw new RuntimeException("获取当前登录用户信息失败");
        }
        if (userId.equals(followUserId)){
            return Result.fail("不可以关注自己");
        }
        if (BooleanUtil.isTrue(isFollow)) {
//            关注
            Follow follow = new Follow().setFollowUserId(followUserId).setUserId(userId);
            boolean isSuccess = save(follow);
            if (isSuccess){
//                记录到redis
                String key = RedisConstants.USER_FOLLOW_KEY + followUserId;
                stringRedisTemplate.opsForSet().add(key, userId.toString());
            }
        }else {
//            取关
            boolean isSuccess = remove(new LambdaQueryWrapper<Follow>()
                    .eq(Follow::getFollowUserId, followUserId)
                    .eq(Follow::getUserId, userId));
            if (isSuccess){
//                从redis中删除
                String key = RedisConstants.USER_FOLLOW_KEY + followUserId;
                stringRedisTemplate.opsForSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        if (followUserId == null) {
            throw new RuntimeException("参数传递错误");
        }
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            throw new RuntimeException("获取当前登录用户信息失败");
        }
        long count = count(new LambdaQueryWrapper<Follow>()
                .eq(Follow::getFollowUserId, followUserId)
                .eq(Follow::getUserId, userId));
        return Result.ok(count > 0);
    }

    @Override
    public Result common(Long id) {
        if (id == null) {
            return Result.fail("参数传递异常");
        }
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            throw new RuntimeException("读取用户信息错误");
        }
        String key1 = RedisConstants.USER_FOLLOW_KEY + userId;
        String key2 = RedisConstants.USER_FOLLOW_KEY + id;

        Set<String> intersection = stringRedisTemplate.opsForSet().intersect(Arrays.asList(key1, key2));
        if (intersection == null || intersection.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<UserDto> userDtoList = intersection.stream().map((item) -> {
            Long commonUserId = Long.valueOf(item);
            User user = userService.getById(commonUserId);
            return BeanUtil.copyProperties(user, UserDto.class);
        }).collect(Collectors.toList());

        return Result.ok(userDtoList);
    }
}
